package poem.by_writer_type_JDBC.Task.utils;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/*解析每一首古诗页面的详情信息*/
public class ParseDetailedUrl {
    public void parseUrl(String url) throws Exception{
        PreparedStatement pstmt = null;
        Connection connection = null;
        try {
            //获取连接
            connection = JdbcUtils.getConnection();
            //开启事务
            connection.setAutoCommit(false);
            //定义sql
            String sql = "insert into poems_jdbc_2 values(null, ?, ?, ?, ?, ?, DEFAULT)";
            pstmt = connection.prepareStatement(sql);
            //解析详情页url
            Document document = null;
            try {
                document = Jsoup.parse(new URL(url), 100000);
            } catch (Exception e) {
                System.out.println(url + "无法解析！");
            }
            //获取诗歌名字
            String title = null;
            try {
                title = document.select("#sonsyuanwen > div.cont > h1").text();
            } catch (Exception e) {
                System.out.println(url + "中的title无法解析！");
            }
            pstmt.setString(1, title);
            //获取作者姓名
            String name = null;
            try {
                name = document.select("#sonsyuanwen > div.cont > p > a:nth-child(1)").text();
            } catch (Exception e) {
                System.out.println(url + "中的name无法解析！");
            }
            pstmt.setString(2, name);
            //获取作者朝代
            String dynasty = null;
            try {
                dynasty = document.select("#sonsyuanwen > div.cont > p > a:nth-child(2)").text().replace("〔", "")
                        .replace("〕", "");
            } catch (Exception e) {
                System.out.println(url + "中的dynasty无法解析！");
            }
            pstmt.setString(3, dynasty);
            //获取诗歌原文
            String content = null;
            try{
                content = document.select("div.contson").first().text();
            } catch (Exception e) {
                System.out.println(url + "中的content无法解析！" );
            }
            pstmt.setString(4, content);
            //保存url
            pstmt.setString(5, url);
            pstmt.executeUpdate();
            //提交事务
            connection.commit();
        } catch (Exception e) {
            //关闭事务
            try {
                if(connection != null)  connection.close();
            } catch (SQLException se) {
                se.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            JdbcUtils.close(pstmt, connection);
        }
   }
}
